import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ZhStatus } from './jq.entities';
import * as nodemailer from 'nodemailer';
@Injectable()
export class AppService {
  constructor(
    @InjectRepository(ZhStatus)
    private readonly zhRepository: Repository<ZhStatus>,
  ) {}
  async createOrUpdate(zhStatus: ZhStatus): Promise<string> {
    try {
      const zhobj = await this.zhRepository.findOneBy({
        todesk: zhStatus.todesk,
        date: zhStatus.date,
      });
      if (zhobj) {
        zhobj.createdAt = new Date().getTime().toString();
        zhobj.timeout = zhStatus.timeout;
        zhobj.bz = zhStatus.bz;
        await zhobj.save();
      } else {
        const curZh = {} as ZhStatus;
        curZh.todesk = zhStatus.todesk;
        curZh.date = zhStatus.date;
        curZh.timeout = zhStatus.timeout;
        curZh.bz = zhStatus.bz;
        curZh.createdAt = new Date().getTime().toString();
        await this.zhRepository.insert(curZh);
      }
      return 'ok';
    } catch (error) {
      console.log(error);

      return error.message;
    }
  }
  async updateEmail(todesk: string, date: string, isSendEmail: string) {
    const zhobj = await this.zhRepository.findOneBy({
      todesk: todesk,
      date: date,
    });
    zhobj.isSendEmail = isSendEmail;
    await zhobj.save();
  }
  async getZh(date: string) {
    const zhobj = await this.zhRepository.findBy({
      date: date,
    });
    return zhobj;
  }

  async sendEmail(todesk: string) {
    const transporter = nodemailer.createTransport({
      host: 'smtp.qq.com', // 你的SMTP服务器地址
      port: 465, // 端口号，例如587或465等
      secure: true, // 如果使用SSL，设置为true；如果是TLS（推荐），设置为false
      auth: {
        user: '602238937@qq.com', // 你的邮箱地址
        pass: 'isacaawivtzwbfig', // 你的邮箱密码或授权码（例如Google的APP密码）
      },
    });
    const mailOptions = {
      from: '602238937@qq.com', // 发件人地址和名称
      to: '1401052762@qq.com', // 收件人地址，可以是字符串或数组（多个收件人）
      subject: '程序运行超时', // 邮件主题
      text: '机器是:' + todesk, // 邮件正文（纯文本）
    };
    await transporter.sendMail(mailOptions);
  }
}
